package com.android.jingweiapp.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.jingweiapp.R;
import com.android.jingweiapp.XMLPhase.GetSpecialSecondXMLPhase;
import com.android.jingweiapp.XMLPhase.GetTopicSecondXMLPhase;
import com.android.jingweiapp.adapter.TopicAdapter2;
import com.android.jingweiapp.bean.TopicBean;
import com.android.jingweiapp.bean.TopicSecondBean;
import com.android.jingweiapp.util.Contacts;
import com.android.jingweiapp.util.HttpUtil;
import com.android.jingweiapp.widget.MyToast;
import com.google.gson.Gson;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

public class TopicSecondActivity extends AppCompatActivity {


    @Bind(R.id.btn_back)
    Button btnBack;
    @Bind(R.id.scrollView)
    LinearLayout scrollView;
    @Bind(R.id.list)
    ListView list;


    private ArrayList<TopicSecondBean.DataEntity> newsBeans;
    private int offset = 1;
    private TopicAdapter2 adapter;
    private RelativeLayout layoutFooter;
    private MySpecialAsyncTask mySpecialAsyncTask;
    private MyTopicAsyncTask myTopicAsyncTask;
    private boolean needLoading = true;
    private boolean isLoading = false;


    private TopicBean.DataEntity dataEntity;
    private int type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topic_second);
        ButterKnife.bind(this);
        init();
    }

    private void init() {

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        newsBeans = new ArrayList<>();
        adapter = new TopicAdapter2(newsBeans, this);
        list.setAdapter(adapter);
        layoutFooter = (RelativeLayout) LayoutInflater.from(this).inflate(
                R.layout.listview_footer, null);
        list.addFooterView(layoutFooter);

        list.setOnScrollListener(new MyOnScrollListener());

        dataEntity = getIntent().getParcelableExtra(Contacts.KEY.KEY_OBJECT);
        type = getIntent().getIntExtra(Contacts.KEY.KEY_TYPE, 0);

        if (dataEntity.getSecondList().size() > 1) {
            for (int j = 0; j < dataEntity.getSecondList().size(); j++) {
                createScrollar(dataEntity.getSecondList().get(j).getSecondName()
                        , dataEntity.getSecondList().get(j).getId());
            }
        }

        if (type == 0) {
            list.setOnItemClickListener(new SpecialOnItemClickListener());
            mySpecialAsyncTask = new MySpecialAsyncTask();
            mySpecialAsyncTask.execute(dataEntity.getSecondList().get(0).getId());
        } else {
            list.setOnItemClickListener(new TopicOnItemClickListener());
            myTopicAsyncTask = new MyTopicAsyncTask();
            myTopicAsyncTask.execute(dataEntity.getSecondList().get(0).getId());
        }

    }

    private void createScrollar(String text, String id) {
        TextView textView = new TextView(this);
        textView.setGravity(Gravity.CENTER);
        textView.setPadding(16, 8, 16, 8);
        // textView.setTextColor(getResources().getColor(R.color.text_color));
        textView.setText(text);
        textView.setGravity(Gravity.CENTER);
        textView.setTag(id);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type == 0) {
                    mySpecialAsyncTask = new MySpecialAsyncTask();
                    mySpecialAsyncTask.execute(v.getTag().toString());
                } else {
                    myTopicAsyncTask = new MyTopicAsyncTask();
                    myTopicAsyncTask.execute(v.getTag().toString());
                }

            }
        });

        LinearLayout.LayoutParams layoutParams =
                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT);
        scrollView.addView(textView, layoutParams);
    }

    private void dealData(String result) {
        newsBeans.clear();
        layoutFooter.setVisibility(View.GONE);
        if (TextUtils.isEmpty(result)) {
            MyToast.getInstance().show("出错了，请重试");
            return;
        }
        if (result.equals("nodata")) {
            needLoading = false;
            if (adapter.getCount() > 0) {
                MyToast.getInstance().show("出错了，请重试");
            } else {
                MyToast.getInstance().show("无更多数据");
            }
            return;
        }
        Gson gson = new Gson();
        TopicSecondBean bean = gson.fromJson(result, TopicSecondBean.class);
        newsBeans.addAll(bean.getData());
        if (bean.getData().size() < 20) {
            needLoading = false;
        }
        adapter.notifyDataSetChanged();
        isLoading = false;
    }

    class TopicOnItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            startActivity(new Intent(TopicSecondActivity.this, NewsDetailPicActivity.class)
                    .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(position))
                    .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.TOPIC_NEWS));
        }
    }

    class SpecialOnItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            startActivity(new Intent(TopicSecondActivity.this, NewsDetailPicActivity.class)
                    .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(position))
                    .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.SPECIAL_NEWS));
        }
    }

    class MyOnScrollListener implements AbsListView.OnScrollListener {
        private int lastItemIndex;


        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (needLoading && !isLoading && lastItemIndex >= adapter.getCount() - 3) {
                layoutFooter.setVisibility(View.VISIBLE);
                offset++;
                mySpecialAsyncTask = new MySpecialAsyncTask();
                mySpecialAsyncTask.execute();
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                             int totalItemCount) {
            lastItemIndex = firstVisibleItem + visibleItemCount - 2;
        }
    }

    class MySpecialAsyncTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            isLoading = true;
        }


        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    GetSpecialSecondXMLPhase.createParam(TopicSecondActivity.this, String.valueOf(offset), params[0]),
                    new GetSpecialSecondXMLPhase());

        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            dealData(str);
        }
    }


    class MyTopicAsyncTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            isLoading = true;
        }


        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    GetTopicSecondXMLPhase.createParam(TopicSecondActivity.this, String.valueOf(offset), params[0]),
                    new GetTopicSecondXMLPhase());

        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            dealData(str);
        }
    }


}
